package com.gdip.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gdip.common.AppJwtUtil;
import com.gdip.common.dtos.ResponseResult;
import com.gdip.common.enums.AppHttpCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

// 验证JWT令牌的有效性
public class JwtInterceptor implements HandlerInterceptor {
    private static final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");



        if (token == null||token.isEmpty()){
            try {
                ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
                String jsonResponse = objectMapper.writeValueAsString(result);
                response.getWriter().write(jsonResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;

        }else {
            System.out.println("token"+token);
            Boolean verify = AppJwtUtil.verify(token);

            if (!verify) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");

                try {
                    ResponseResult result = ResponseResult.errorResult(HttpServletResponse.SC_UNAUTHORIZED, "无效的令牌");
                    String jsonResponse = objectMapper.writeValueAsString(result);
                    response.getWriter().write(jsonResponse);
                    System.out.println(jsonResponse);
                } catch (Exception e) {
                    return false;
                }

            }

        }

        return true;
    }
}